﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Bookkeeping.Mvc.Models.Budget;
using Bookkeeping.Core.Entities;
using Bookkeeping.Core.Persistence;
using Bookkeeping.Persistence.Repositories;
using Bookkeeping.Core.Services;

namespace Bookkeeping.Mvc.Controllers
{
    [HandleError]
    public class BudgetController : Controller
    {
        DateTime _date;

        public ActionResult List(int? year, int? month, int? selectedId)
        {
            _date = CreateDate(year, month);
            Budget budget = LoadBudget();

            var listViewModel = new ListViewModel()
            {
                MonthNavigation = CreateMonthNavigation(_date),
                Total = new TotalViewModel(budget.TotalIncludingSavings, budget.TotalExcludingSavings),
                Expenses = new PostListViewModel(budget.Expenses, "Expenses", budget.TotalExpenses),
                Incomes = new PostListViewModel(budget.Incomes, "Incomes", budget.TotalIncomes),
                Savings = new PostListViewModel(budget.Savings, "Savings", budget.TotalSavings),
                Year = _date.Year,
                Month = _date.Month
            };

            if (selectedId.HasValue)
                listViewModel.SelectPostById(selectedId.Value);

            return View(listViewModel);
        }

        private MonthNavigationViewModel CreateMonthNavigation(DateTime date)
        {
            return new MonthNavigationViewModel()
            {
                Date = _date,
                PreviousMonthDate = DateTimeHelper.GetPreviousMonth(_date),
                NextMonthDate = DateTimeHelper.GetNextMonth(_date)
            };
        }

        private static DateTime CreateDate(int? year, int? month)
        {
            if (year.HasValue && month.HasValue)
                return new DateTime(year.Value, month.Value, 1);

            return DateTime.Now;
        }

        private Budget LoadBudget()
        {
            using (IPersistenceContext context = new PersistenceContext())
            {
                var posts = context.Posts.GetAllByMonthWithTagsLoaded(_date);

                return new Budget(posts);
            }
        }
    }
}
